/*
 * @(#)UpgradeAction.java
 * 2011-9-24 下午09:36:30
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.attach.web;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;

import com.qyxx.platform.common.json.JsonOutput;
import com.qyxx.platform.common.module.web.CrudActionSupport;
import com.qyxx.platform.common.module.web.Messages;
import com.qyxx.platform.common.utils.web.struts2.Struts2Utils;
import com.qyxx.platform.gsc.utils.SystemParam;
import com.qyxx.platform.sysmng.accountmng.entity.User;
import com.qyxx.platform.sysmng.attach.service.AttachManager;
import com.qyxx.platform.sysmng.utils.Constants;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * 附件上传处理类
 */

@Namespace("/sys/attach")
public class UploadFileAction extends CrudActionSupport<File> {
	private static final long serialVersionUID = -3214199305972555680L;

	private File filedata;

	private File[] file;

	private String filedataFileName = "";
	
	private SystemParam systemParam;
	
	private AttachManager attachManager;
	
	private Long attachId;
	
	private String filePath = ""; //文件相对路径
	
	private Integer chunk = 0; //当前文件分片序号，从0开始分片
	
	private Integer chunks; //文件分片数
	
	private Integer chunkSize; //文件分片大小
	
	private String uuid; //单个文件分片上传唯一标识
	
	public Long getAttachId() {
		return attachId;
	}

	public void setAttachId(Long attachId) {
		this.attachId = attachId;
	}

	public void setAttachManager(AttachManager attachManager) {
		this.attachManager = attachManager;
	}

	public SystemParam getSystemParam() {
		return systemParam;
	}

	public void setSystemParam(SystemParam systemParam) {
		this.systemParam = systemParam;
	}
	/**
	 * @return filedata
	 */
	public File getFiledata() {
		return filedata;
	}

	/**
	 * @param filedata
	 */
	public void setFiledata(File filedata) {
		this.filedata = filedata;
	}

	/**
	 * @return filedataFileName
	 */
	public String getFiledataFileName() {
		return filedataFileName;
	}

	/**
	 * @param filedataFileName
	 */
	public void setFiledataFileName(String filedataFileName) {
		this.filedataFileName = filedataFileName;
	}


	/**
	 * @return filePath
	 */
	public String getFilePath() {
		return filePath;
	}

	public File[] getFile() {
		return file;
	}

	public void setFile(File[] file) {
		this.file = file;
	}


	/**
	 * @param filePath
	 */
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	/**
	 * @return chunk
	 */
	public Integer getChunk() {
		return chunk;
	}

	
	/**
	 * @param chunk
	 */
	public void setChunk(Integer chunk) {
		this.chunk = chunk;
	}

	
	/**
	 * @return chunks
	 */
	public Integer getChunks() {
		return chunks;
	}

	
	/**
	 * @param chunks
	 */
	public void setChunks(Integer chunks) {
		this.chunks = chunks;
	}

	
	/**
	 * @return chunkSize
	 */
	public Integer getChunkSize() {
		return chunkSize;
	}

	
	/**
	 * @param chunkSize
	 */
	public void setChunkSize(Integer chunkSize) {
		this.chunkSize = chunkSize;
	}

	
	/**
	 * @return uuid
	 */
	public String getUuid() {
		return uuid;
	}

	
	/**
	 * @param uuid
	 */
	public void setUuid(String uuid) {
		this.uuid = uuid;
	}

	@Override
	public String list() throws Exception {
		return SUCCESS;
	}

	@JsonOutput
	@Override
	public String input() throws Exception {
		// TODO Auto-generated method stub
		String fileForderName = DateFormatUtils.format(new Date(),
				"yyyyMMdd");
		String filePackage = systemParam.getUploadPicPath()
				+ com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_PATH;
		String name = Struts2Utils.getParameter("name");
		String filePath = com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_IMAGE
				+ fileForderName
				+ com.qyxx.platform.gsc.utils.Constants.PATH_SEPARATOR
				+ DateFormatUtils.format(System.currentTimeMillis(),
						"yyyyMMddHHmmssSSS")
				+ StringUtils.substring(name, name.lastIndexOf("."));
		//如果文件夹不存在则创建    
		//File file = new File(filePackage + com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_IMAGE + fileForderName);    
		//FileUtils.forceMkdir(file);
		File destFile = new File(filePackage + filePath);
		
		/*OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(destFile)); 
		InputStream inputStream = ServletActionContext.getRequest().getInputStream();
		byte[] buffer = new byte[8192];
		int readIndex;
		while(-1 != (readIndex = inputStream.read(buffer, 0, buffer.length))) {
			outputStream.write(buffer, 0, readIndex);
		}
        outputStream.close();*/
		
		InputStream inputStream = ServletActionContext.getRequest().getInputStream();
        FileUtils.copyInputStreamToFile(inputStream, destFile);
		formatMessage.setMsg(filePath);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	@JsonOutput
	public  String upload() throws Exception {
		// TODO Auto-generated method stub
		String fileForderName = DateFormatUtils.format(new Date(),
				"yyyyMMdd");
		String filePackage = systemParam.getUploadPicPath()
				+ com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_PATH;
		//String name = Struts2Utils.getParameter("name");
		String filePath = com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_IMAGE
				+ fileForderName
				+ com.qyxx.platform.gsc.utils.Constants.PATH_SEPARATOR
				+ DateFormatUtils.format(System.currentTimeMillis(),
				"yyyyMMddHHmmssSSS");


		DiskFileItemFactory factory  = new DiskFileItemFactory();
		factory.setSizeThreshold(1024*1024);
		File file = new File("f:\\");
		factory.setRepository(file);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(1024*1024*5);
		upload.setHeaderEncoding("UTF-8");
			HttpServletRequest request = ServletActionContext.getRequest();
			List<FileItem> fileItem = upload.parseRequest(request);
			for(FileItem fileItem2 :fileItem){
			 String name = fileItem2.getName();
				String fileUrl = filePackage + filePath+StringUtils.substring(name, name.lastIndexOf("."));
			 Long size = fileItem2.getSize();
				InputStream in = fileItem2.getInputStream();
				byte[]  buffer = new byte[1024];
			 int  len = 0;
			// String fileUrl = "f:\\"+name;
			 OutputStream out = new FileOutputStream(fileUrl);
			 while((len=in.read(buffer))!=-1){
			 	out.write(buffer,0,len);
			 }
			 out.close();
			 in.close();
		 }

		formatMessage.setMsg(filePath);
		Struts2Utils.renderJson(formatMessage);
         return  null;

	}


	/**
	 * 保存上传的文件 uploadify客户端调用
	 * @see com.qyxx.platform.common.module.web.CrudActionSupport#save()
	 */
	@JsonOutput
	@Override
	public String save() throws Exception {
		//向SYS_ATTACHE_LIST表插入数据
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		Long id = Constants.SUPER_ADMIN_USER_ID; 
		if(null!=user) id = user.getId();
		String attId = attachManager.saveFile(attachId,filedata,filedataFileName,systemParam,id);
		formatMessage.setMsg(attId);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 保存上传文件分片，WebUploader客户端调用
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String saveFile() throws Exception {
		String filePackage = systemParam.getUploadPicPath()
				+ com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_PATH;
		String filePath = com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_TEMP + 
					uuid + com.qyxx.platform.gsc.utils.Constants.PATH_SEPARATOR + chunk;
		File destFile = new File(filePackage + filePath);
		InputStream inputStream = ServletActionContext.getRequest().getInputStream();
        FileUtils.copyInputStreamToFile(inputStream, destFile);
		formatMessage.setMsg(filePath);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 合并上传文件及记录，WebUploader客户端调用
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String mergeFile() throws Exception {
		// 向SYS_ATTACHE_LIST表插入数据
		User user = (User) Struts2Utils
				.getSessionAttribute(Constants.USER_SESSION_ID);
		Long userId = Constants.SUPER_ADMIN_USER_ID;
		if (null != user)
			userId = user.getId();
		String filePackage = systemParam.getUploadPicPath()
				+ com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_PATH;
		String filePath = com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_TEMP + 
					uuid + com.qyxx.platform.gsc.utils.Constants.PATH_SEPARATOR;
		String tempDirPath = filePackage + filePath;
		File dir = new File(tempDirPath);
		if(dir.exists() && dir.isDirectory()) {
			int len = dir.list().length;
			if(len == chunks) {
				File destFile = new File(tempDirPath + filedataFileName);
				for(int i=0;i<chunks;i++) {
					FileUtils.writeByteArrayToFile(destFile, FileUtils.readFileToByteArray(new File(tempDirPath + i)), true);
				}
				String attId = attachManager.saveFile(attachId, destFile,
						filedataFileName, systemParam, userId);
				formatMessage.setMsg(attId);
				try {
					FileUtils.forceDelete(dir);
				} catch(Exception e) {
					logger.error("删除临时文件夹" + dir + "出现异常", e);
				}
			} else {
				formatMessage.setFlag(Messages.ERROR);
				formatMessage.setMsg("Chunks of dir " + tempDirPath + " is " + len + ", but the upload file chunks is " + chunks + ".");
			}
		} else {
			formatMessage.setFlag(Messages.ERROR);
			formatMessage.setMsg("The dir " + tempDirPath + " does not exists.");
		}
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	@Override
	public String view() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String delete() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void prepareModel() throws Exception {
		// TODO Auto-generated method stub

	}
	
	@JsonOutput
	public String saveImage() throws Exception {
		// TODO Auto-generated method stub
		String fileForderName = DateFormatUtils.format(new Date(),
				"yyyyMMdd");
		String filePackage = systemParam.getUploadPicPath()
				+ com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_PATH;
		String filePath = com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_IMAGE
				+ fileForderName
				+ com.qyxx.platform.gsc.utils.Constants.PATH_SEPARATOR
				+ DateFormatUtils.format(System.currentTimeMillis(),
						"yyyyMMddHHmmssSSS")
				+ filedataFileName.substring(
						filedataFileName.lastIndexOf("."),
						filedataFileName.length());
		File destFile = new File(filePackage + filePath);

		FileUtils.copyFile(filedata, destFile);
		formatMessage.setMsg(filePath);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}


	@JsonOutput
	public String saveImageByApp() throws Exception {
		// TODO Auto-generated method stub
		List<String> filePathList = new ArrayList<>();
		for(File f:file){
       	  String  name =  f.getName();
		   String fileForderName = DateFormatUtils.format(new Date(),
				   "yyyyMMdd");
		   String filePackage = systemParam.getUploadPicPath()
				   + com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_PATH;
		   String filePath = com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_IMAGE
				   + fileForderName
				   + com.qyxx.platform.gsc.utils.Constants.PATH_SEPARATOR
				   + DateFormatUtils.format(System.currentTimeMillis(),
				   "yyyyMMddHHmmssSSS")
				   + name.substring(
				   name.lastIndexOf("."),
				   name.length());
		   File destFile = new File(filePackage + filePath);
		   FileUtils.copyFile(f, destFile);
		   filePathList.add(filePath);
       }


		formatMessage.setMsg(filePathList);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	/**
	 * 下载文件
	 * 
	 * @return
	 * @throws Exception
	 */
	public String downloadFile() throws Exception {
		String fileName = this.filedataFileName;
		String filePackage = systemParam.getUploadPicPath()
							+ com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_PATH;
		String absFilePath = filePackage + this.filePath;
		Struts2Utils.writeFile(fileName, absFilePath, false);
		return null;
	}
	 
}
